<?php

  // Requires Facebook PHP SDK 3.0.1: https://github.com/facebook/php-sdk/
  require ('includes/facebook.php');

  define('FACEBOOK_APP_ID',"160596754040030");
  define('FACEBOOK_SECRET',"20ea9c13cac64e709f346cac489669f9");

  $user = null;

  // Create our Application instance (replace this with your appId and secret).
  $facebook = new Facebook(array(
  'appId' => FACEBOOK_APP_ID,
  'secret' => FACEBOOK_SECRET,
  'cookie' => true
  ));

  $user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.

  if($user == 0) {

    /**
    * Get a Login URL for use with redirects. By default, full page redirect is
    * assumed. If you are using the generated URL with a window.open() call in
    * JavaScript, you can pass in display=popup as part of the $params.
    * 
    * The parameters:
    * - redirect_uri: the url to go to after a successful login
    * - scope: comma separated list of requested extended perms
    */

    $login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));

    echo ("<script> top.location.href='".$login_url."'</script>");

  } else {

    try {
      
      $user_profile = $facebook->api('/me'); 

      $dbhost = "127.0.0.1";
      $dbname = "test_facebook";
      $dbuser = "root";
      $dbpass = "";

      mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
      mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

      $request_id = mysql_real_escape_string( md5( $user . microtime(true) . time() . $user) );  
      $created_time = time();
      $expired_time = time() + 86400;
      
      mysql_query("INSERT INTO fb_requests (
      `request_id`,  
      `recipient_uid`,
      `sender_uid`,
      `remaining_time`,
      `request_token`,
      `created_time`, 
      `expired_time`,
      ) VALUES ( '$user', '$request_id', null, 1, null, $created_time, $expired_time );") or die("MySQL Error: " . mysql_error());

      $params = array(
      'message'       =>  $user_profile['name'] . ' nhận được ',
      'name'          =>  "This is my title",
      'caption'       =>  "My Caption",
      'description'   =>  "Some Description...",
      'link'          =>  "http://stackoverflow.com",
      'picture'       =>  "http://i.imgur.com/VUBz8.png",
      );

      $post = $facebook->api("/$user/feed", "POST", $params);
      var_dump($post);
      echo "Your post was successfully posted to UID: $user";

    }
    catch (FacebookApiException $e) {
      $result = $e->getResult();
    }

  }

?> 